﻿using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Basefr.Data.EntityFrameworkCore;
using System;
using System.Linq;

namespace Basefr.Web.Data
{
    public static class DatabaseInitializer
    {
        public static IApplicationBuilder CreateDatabase<TDbContext>(this IApplicationBuilder app, Action<TDbContext> dataInitializer = null)
            where TDbContext : DbContext<TDbContext>
        {
            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService<TDbContext>();

                context.Database.EnsureCreated();  //建库

                dataInitializer?.Invoke(context);  //允许外部传进来一个Action，用于初始化数据
            }

            return app;
        }

        public static IApplicationBuilder MigrateDatabase<TDbContext>(this IApplicationBuilder app, Action<TDbContext> dataInitializer = null)
            where TDbContext : DbContext<TDbContext>
        {
            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService<TDbContext>();

                if (context.Database.GetPendingMigrations().Any())
                {
                    context.Database.Migrate();
                }

                dataInitializer?.Invoke(context);  //允许外部传进来一个Action，用于初始化数据
            }

            return app;
        }
    }
}
